<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import { ElMessage } from 'element-plus'
import { login } from '@/api/auth'

const router = useRouter()

const loginForm = ref({
  username: '',
  password: ''
})

const loading = ref(false)
const errorMsg = ref('')

const validateForm = () => {
  if (!loginForm.value.username.trim()) {
    errorMsg.value = '请输入用户名'
    return false
  }
  if (!loginForm.value.password.trim()) {
    errorMsg.value = '请输入密码'
    return false
  }
  return true
}

const handleLogin = async () => {
  try {
    if (!validateForm()) return

    loading.value = true
    errorMsg.value = ''
    
    const { data } = await login(loginForm.value)

    // 存储token
    localStorage.setItem('token', data.token)

    // 可以添加提示信息
    ElMessage.success('登录成功')

    // 登录成功后跳转
    router.push('/')

  } catch (error: any) {
    errorMsg.value = error.message || '登录失败，请重试'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="min-h-screen bg-gray-100">
    <!-- 顶部标题栏 -->
    <div class="bg-blue-400 text-white text-center py-4 text-lg">
      用户登录
    </div>
    
    <!-- 登录表单 -->
    <div class="px-4 py-5">
      <div class="space-y-4">
        <!-- 手机号输入框 -->
        <div>
          <input
            v-model.trim="loginForm.username"
            type="text"
            placeholder="用户名"
            class="w-full px-3 py-3 border border-gray-200 rounded-md text-base focus:outline-none focus:border-blue-400"
          >
        </div>
        
        <!-- 密码输入框 -->
        <div>
          <input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            class="w-full px-3 py-3 border border-gray-200 rounded-md text-base focus:outline-none focus:border-blue-400"
          >
        </div>

        <!-- 错误信息 -->
        <div v-if="errorMsg" class="text-red-500 text-center text-sm">
          {{ errorMsg }}
        </div>

        <!-- 登录按钮 -->
        <button
          @click="handleLogin"
          :disabled="loading"
          class="w-full py-3 bg-green-500 text-white rounded-md text-base mt-6 disabled:opacity-50"
        >
          {{ loading ? '登录中...' : '登陆' }}
        </button>

        <!-- 注册链接 -->
        <div 
          class="mt-4 text-center py-3 bg-gray-100 rounded-md"
        >
          <a href="/register" class="text-gray-600">去注册</a>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>